package com.diaohw.module.system.mapper;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.diaohw.module.system.obj.entity.Account;
import com.diaohw.module.system.obj.query.AccountQuery;
import com.diaohw.module.system.obj.tables.AccountRoleDef;
import com.mybatisflex.core.BaseMapper;
import com.mybatisflex.core.query.QueryWrapper;
import org.apache.ibatis.annotations.Mapper;

import static com.diaohw.module.system.obj.tables.AccountDef.ACCOUNT;
import static com.diaohw.module.system.obj.tables.AccountRoleDef.ACCOUNT_ROLE;
import static com.diaohw.module.system.obj.tables.RoleDef.ROLE;

/**
 * 用户 映射层。
 *
 * @author D-Hw
 * @since 2024-11-15 18:22:15
 */
@Mapper
public interface AccountMapper extends BaseMapper<Account> {


    static QueryWrapper createWrapper(AccountQuery query) {
        QueryWrapper wrapper = QueryWrapper.create();
        wrapper.select(ACCOUNT.AllColumns)
                .from(ACCOUNT.as("A"));

        AccountRoleDef ar = ACCOUNT_ROLE.as("AR");
        if (StrUtil.isNotBlank(query.getRoleType())) {
            wrapper.leftJoin(ar).on(ar.ACCOUNT_ID.eq(ACCOUNT.ID))
                    .leftJoin(ROLE.as("R")).on(ROLE.ID.eq(ar.ROLE_ID))
                    .and(ROLE.ROLE_TYPE.eq(query.getRoleType()))
                    .and(ROLE.ID.in(query.getRoleIds()).when(CollectionUtil.isNotEmpty(query.getRoleIds())));
        } else if (query.getRoleIds() != null && !query.getRoleIds().isEmpty()) {
            wrapper.leftJoin(ar).on(ar.ACCOUNT_ID.eq(ACCOUNT.ID));
            wrapper.and(ar.ROLE_ID.in(query.getRoleIds()));
        }
        wrapper.and(ACCOUNT.STATE.eq(query.getState()).when(ObjUtil.isNotNull(query.getState())));
        wrapper.and(ACCOUNT.NICKNAME.like(query.getNickname()).when(StrUtil.isNotBlank(query.getNickname())));
        wrapper.and(ACCOUNT.USERNAME.eq(query.getUsername()).when(StrUtil.isNotBlank(query.getUsername())));

        return wrapper;
    }
}
